import { Body, Controller, Get, Post, Req, Res, Put, UseGuards, HttpException, HttpStatus, Param } from '@nestjs/common';
import { UserService } from './user.service'
import { Request, Response } from 'express'
import { AuthGuard } from '../../guard/auth.guard'
import { ValidationPipe } from '../../pipes/validate.pipe'
import { UpdateUserDto } from './dtos/update-user.dto'
import { IsUppercase, isNumber } from 'class-validator';

interface CustomRequest extends Request {
    userId: string
}

@Controller('user')
export class UserController {
    constructor(
        private readonly userService: UserService
    ) { }

    @Get()
    @UseGuards(AuthGuard)
    getInfo(@Req() req) {
        return this.userService.getInfo(req.userId)
    }

    @Get('/all')
    @UseGuards(AuthGuard)
    getInfoAll(@Body() body) {
        let { page = 1, limit = 10, order = "" } = body
        page = Number(page)
        limit = Number(limit)
        if (isNaN(page) || isNaN(limit)) {
            throw new HttpException('page 和 limit 必须是数字', HttpStatus.BAD_REQUEST)
        }

        return this.userService.getInfoAll(page, limit, order)
    }

    @Get(':id')
    getInfoById(@Param('id') id) {
        return this.userService.getInfoById(id)
    }



    @Put()
    @UseGuards(AuthGuard)
    putInfo(@Req() req: CustomRequest, @Body(new ValidationPipe) updateUserDto: UpdateUserDto) {
        const userId = req.userId
        console.log(userId)

        return this.userService.putInfo(userId, this.removeEmptyEntries(updateUserDto))

    }

    // 属性为空删除
    removeEmptyEntries(obj) {
        let newObj = {};

        for (let key in obj) {
            let value = obj[key];

            // 检查值是否为空，这里的判断依据是题目所给的要求，可以自行调整
            if (
                value !== null &&
                value !== undefined &&
                value !== '' &&
                (Array.isArray(value) ? value.length > 0 : true)
                //  && (typeof value === 'object' ? !Object.keys(value).length === 0 : true)
            ) {
                if (typeof value === 'object' && value !== null) {
                    newObj[key] = this.removeEmptyEntries(value);
                } else {
                    newObj[key] = value;
                }
            }
        }

        return newObj;
    }
}
